<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\order;

use app\common\model\GoodsOrder;

/**
 * service 订单服务
 */
class OrderService
{

    /**
     * 完成订单
     * @param GoodsOrder $order
     * @return array
     */
    public function complete(&$order)
    {
        if (empty($order)) {
            throw new \Exception("订单不存在");
        }
        if ($order->status != 0) {
            throw new \Exception("该订单不是未支付状态");
        }
        $order->status     = 1;
        $order->success_at = date('Y-m-d H:i:s');
        $order->save();
        // 销量统计
        $order->goods()->update(['sales_volume' => $order->goods->sales_volume + $order->quantity]);
        return $order->toArray();
    }

    /**
     * 查找
     */
    public function findOrder($trade_no)
    {
        $order = GoodsOrder::where(['trade_no' => $trade_no])->find();
        if (!$order) {
            throw new \Exception("订单不存在");
        }
        return $order;
    }

    /**
     * 获取订单状态
     */
    public function orderStatus($trade_no)
    {
        $order = $this->findOrder($trade_no);
        return $order->status;
    }

    /**
     * 关闭订单
     * Timeer 计时关闭订单
     * @param $trade_no
     */
    public function closeOrder($trade_no)
    {
        $order = $this->findOrder($trade_no);
        if ($order->status == 0) {
            $order->status = 2;
            $order->save();
        }
    }
}
